import { RendererFactory2, Injectable, Renderer2 } from '@angular/core';
import { NzModalService } from "ng-zorro-antd";
import { ModalOptionsForService, NzModalRef, NzModalComponent } from 'ng-zorro-antd';


@Injectable({
  providedIn: 'root'
})
export class MetaModalService {
  private render: Renderer2;

  constructor(private modal: NzModalService, rendererFactory: RendererFactory2) {
    this.render = rendererFactory.createRenderer(null, null);
  }

  private dialog;

  create<T>(options: ModalOptionsForService<T> = {}): NzModalComponent {

    this.dialog = this.modal.create(options);
    this.dialog.afterOpen.subscribe(() => {
      //=========================================================

      let _this = this.dialog;
      let elementRef = _this.elementRef;
      let modalElement = elementRef.nativeElement.querySelector('.ant-modal');
      let modalTitleElement = elementRef.nativeElement.querySelector('.ant-modal-header');
      this.render.listen(modalTitleElement, 'mousedown', function (event) {
        _this.mouseDownX = event.clientX;
        _this.mouseDownY = event.clientY;
        _this.modalX = modalElement.offsetLeft;
        _this.modalY = modalElement.offsetTop;
        _this.distX = event.clientX - modalElement.offsetLeft;
        _this.distY = event.clientY - modalElement.offsetTop;
        this.render.setStyle(modalElement, "position", "absolute");
        this.render.setStyle(modalElement, "top", `${ _this.modalY }px`);
        this.render.setStyle(modalElement, "left", `${ _this.modalX }px`);
        _this.canMove = true;
      }.bind(this));
      this.render.listen(modalTitleElement, 'mouseup', function (event) {
        this.render.setStyle(modalTitleElement, "cursor", `default`);
        _this.canMove = false;
      }.bind(this));
      this.render.listen(elementRef.nativeElement, 'mousemove', function (event) {
        if (_this.canMove) {
          let moveX = event.clientX - _this.distX;
          let moveY = event.clientY - _this.distY;
          const modalWidth = modalElement.offsetWidth;
          const modalHeight = modalElement.offsetHeight;
          const cw = document.documentElement.clientWidth;
          const cy = document.documentElement.clientHeight;

          if (moveY < 0) {
            moveY = 0;
          } else if (moveY > cy - modalHeight) {
            moveY = cy - modalHeight;
          }

          if (moveX < 0) {
            moveX = 0;
          } else if (moveX > cw - modalWidth) {
            moveX = cw - modalWidth;
          }

          this.render.setStyle(modalElement, "top", `${ moveY }px`);
          this.render.setStyle(modalElement, "left", `${ moveX }px`);
          this.render.setStyle(modalTitleElement, "cursor", `move`);
        }
      }.bind(this));
      //=========================================================
    });

    return this.dialog;
  }
}
